import datetime
import time

from api_request import send_post_request
from mail_content_builder import build_email_content
from mail_sender import send_email, handle_general_exception
from response_parser import parse_response

# 请求的URL
url = "https://apis.pocketuni.net/apis/activity/list"

# 请求头信息,请求头请登录https://pocketuni.net/任意网页F12任意请求获取
headers = {
    "accept": "application/json, text/plain, */*",
    "accept-encoding": "gzip, deflate, br, zstd",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "authorization": "Bearer X",  # 这里写你自己的Token
    "connection": "keep-alive",
    "content-length": "66",
    "content-type": "application/json",
    "dnt": "1",
    "host": "apis.pocketuni.net",
    "origin": "https://class.pocketuni.net",
    "referer": "https://class.pocketuni.net/",
    "sec-ch-ua": '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
}

# 假设这是要发送的JSON数据，你需要替换成真实数据
data = {
    "sort": 2,
    "page": 1,
    "limit": 10,
    "puType": 0,
    "status": 1
}


def main_task():
    """
    定义主任务函数，包含发送请求、解析响应、构建邮件内容以及发送邮件的完整流程
    """
    try:
        # 发送POST请求
        response = send_post_request(url, headers, data)
        # 解析响应内容
        if response:
            result_dict = parse_response(response)
            if result_dict:
                # 假设这里通过前面的代码已经获取到了result_dict数据，实际中替换成真实获取数据的逻辑
                data_dict = result_dict  # 此处需替换为真实有效的数据字典，比如从请求接口获取并解析后的结果
                subject = "PU口袋校园活动信息数据"
                for i in emails:
                    msg = build_email_content(data_dict, subject, i)
                    send_email(msg)
    except Exception as e:
        handle_general_exception(e)


if __name__ == '__main__':
    # 设置每15分钟执行一次主任务
    # schedule.every(25).minutes.do(main_task)
    emails = ["X@qq.com", "X@qq.com", "X@qq.com", "x@qq.com"]  # 邮箱列表
    while True:
        now = datetime.datetime.now()
        current_hour = now.hour
        # 判断当前小时是否在23点到第二天6点之间（包含23点，不包含6点）
        if current_hour >= 23 or current_hour < 6:
            print("免打扰时段,已跳过当前定时任务执行流程!")
            time.sleep(1800)
            continue
        main_task()
        print("任务执行!")
        time.sleep(1800)
        print("定时任务已启动!")
